<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert title="注意：只允许为第三季分类设置相关参数！" type="warning" :closable="false" show-icon> </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
          <el-col>
                <span>选择商品分类：</span>
                <!-- 级联选择框 -->
                    <!-- v-model 被选中的父级分类id数组 -->
                    <!-- options  绑定的数据源-->
                    <!-- props 配置对象，决定了前台要接收和显示的对象。 -->
                    <!-- checkStrictly 控制级联多选或单选 -->
                    <!-- show-all-levels 控制级联选择器是否显示完整路径 -->
                   <el-cascader
                        v-model="paramsCateKeys"
                        :options="paramsList"
                        :props="{ 
                            expandTrigger: 'hover',
                            value: 'cat_id',
                            label: 'cat_name',
                            children: 'children',
                            checkStrictly: false
                        }"
                        @change="handleChange" clearable show-all-levels>
                    </el-cascader>
          </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true" class="buttonPrimary">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTabData" border stripe>
                <!-- 插入表格行 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{item}}</el-tag>
                        <!-- 动态添加tag标签 -->
                        <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="remoParams(scope.row.attr_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>
            <!-- 静态属性表格 -->
            <el-table :data="onlyTabData" border stripe>
                <!-- 插入表格行 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{item}}</el-tag>
                        <!-- 动态添加tag标签 -->
                        <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="remoParams(scope.row.attr_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
    </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="50%"
         @close="addDialogClosed">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 编辑参数对话框 -->
    <el-dialog
        :title="'编辑' + titleText"
        :visible.sync="editDialogVisible"
        width="50%"
         @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
        // 获取级联数据
        paramsList: [],
        // 级联数据父级的id数组
        paramsCateKeys: [],
        // 被激活的页签名称，默认选择项
        activeName: 'many',
        // 动态数据参数
        manyTabData: [],
        // 静态数据属性
        onlyTabData: [],
        // 添加参数对话框开关
        addDialogVisible: false,
        // 添加参数和属性对话框数据对象
        addForm: {
            attr_name: ''
        },
        // 验证
        addFormRules: {
            attr_name: [
                { required: true, message: '请输入名称', trigger: 'blur' },
                { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
            ]
        },
        // 编辑窗口验证
        editFormRules: {
            attr_name: [
                { required: true, message: '请输入名称', trigger: 'blur' },
                { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
            ]
        },
        // 编辑窗口绑定的name
        editForm: {
            attr_name: ''
        },
        // 编辑窗口开关
        editDialogVisible: false
        // // 插入行内属性tag点击添加标签的开关
        // inputVisible: false,
        // // 双向绑定的value值
        // inputValue: ''
    }
  },
  created() {
    //   获取级联数据函数
      this.getParamsList()
  },
  methods: {
    //   get请求获取数据方式
        async getParamsList() {
            const { data: res } = await this.$http.get('categories')
            if(res.meta.status !== 200) {
                return this.$message.erroe('获取数据失败')
            }
            this.paramsList = res.data
            // console.log(this.paramsList)
        },
        // 级联选择器发生变化时触发，选中级联选择器选项后触发
        handleChange() {
            // console.log(this.paramsCateKeys)
            if(this.paramsCateKeys.length !== 3) {
                this.paramsCateKeys = []
                this.manyTabData = []
                this.onlyTabData = []
                return
            }
            // console.log(this.paramsCateKeys)
            this.getParamsData()
        },
        // 页签 切换触发
        handleClick() {
            this.getParamsData()
        },
        // 获取标签页数据
        async getParamsData() {
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
            if(res.meta.status !== 200) {
                return this.$message.error('获取数据失败')
            }
            // 循环获取的标签页数据，使用split将里面的属性变成数组
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                item.inputVisible = false
                item.inputValue = ''
            })
             // console.log(res.data)
            // 分别获取动态和静态数据
            if(this.activeName == 'many') {
                this.manyTabData = res.data
            }else{
                this.onlyTabData = res.data
            }
        },
        // 监听窗口关闭触发事件
        addDialogClosed() {
            this.$refs.addFormRef.resetFields()
        },
        addParams() {
            // console.log(this.addForm)
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return
                const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
                    attr_name: this.addForm.attr_name,
                    attr_sel: this.activeName
                })
                if(res.meta.status !== 201) {
                    return this.$message.erroe('添加失败')
                }
                this.$message.success('添加成功')
                this.getParamsData()
                this.addDialogVisible = false
            })
        },
        // 关闭编辑窗口触发事件 重置信息
        editDialogClosed() {
            this.$refs.editFormRef.resetFields()
        },
        // 点击确定触发事件
        editParams() {
            this.$refs.editFormRef.validate(async valid => {
                if(!valid) return 
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
                attr_name: this.editForm.attr_name,
                attr_sel: this.activeName
            })
            if(res.meta.status !== 200) {
                return this.$message.error('编辑失败')
            }
            this.$message.success('编辑成功')
            this.getParamsData()
            this.editDialogVisible = false
            })
        },
        // 点击编辑触发事件
        async showEditDialog(id) {
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
                params: {
                    attr_sel: this.activeName
                }
            })
            if(res.meta.status !== 200) {
                return this.$message.error('获取数据失败')
            }
            // console.log(res.data)
            this.editForm = res.data
            this.editDialogVisible = true
        },
        async remoParams(id) {
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 如果用户点击确定删除，返回字符串confirm
            // 如果用户点击取消删除，返回字符串cancel
            if(confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
            if(res.meta.status !== 200) {
                return this.$message.error('删除失败')
            }
            this.$message.success('删除成功')
            this.getParamsData()
        },
        // 失去焦点或者按下enter键触发的事件  trim()去除字符串的头尾空格:
          handleInputConfirm(row) {
            if(row.inputValue.trim() === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            row.inputVisible = false
            this.saveAttrVals(row)
//             const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
//                 attr_name: row.attr_name,
//                 attr_sel: row.attr_sel,
// //                 join方法用于把数组中的所有元素放入一个字符串  使用空格分割将所有内容让如一个字符串内。
//                 attr_vals: row.attr_vals.join(' ')
//             })
//             if(res.meta.status !== 200) {
//                 return this.$message.error('编辑失败')
//             }
//             this.$message.success('编辑成功')
        },
        showInput(row) {
            row.inputVisible = true
            // this.$nextTick当页面上的元素被重新渲染之后才会指定函数中的代码
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },
        async saveAttrVals(row) {
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
//                 join方法用于把数组中的所有元素放入一个字符串  使用空格分割将所有内容让如一个字符串内。
                attr_vals: row.attr_vals.join(' ')
            })
            if(res.meta.status !== 200) {
                return this.$message.error('编辑失败')
            }
            this.$message.success('编辑成功')
        },
        handleClose(i, row) {
            row.attr_vals.splice(i, 1)
            this.saveAttrVals(row)
        }
  },
  computed: {
    //   控制标签页切换 在没有选定三级分类时 禁用添加参数
        isBtnDisabled() {
            if(this.paramsCateKeys.length !== 3) {
                return true
            }
            return false
        },
        // 获取数据时提供的三级分类id
        cateId() {
            if(this.paramsCateKeys.length === 3) {
                return this.paramsCateKeys[2]
            }
            return null
        },
        titleText() {
            if(this.activeName === 'many') {
                return '动态参数'
            }
            return '静态属性'
        }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
    margin: 15px 0;
}
.buttonPrimary{
    margin-bottom: 15px;
}
.el-tag{
    margin: 0 10px
}
.input-new-tag {
    width: 120px;
}
</style>
